using System;
using System.Data.Linq;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.UI;
using octalforty.Componento.Web.Shared.Data;

namespace octalforty.Componento.Web.Repository.Controllers
{
    public class ComponentsController : Controller
    {
        [OutputCache(Location = OutputCacheLocation.Any, Duration = 60, VaryByParam = "*")]
        public ActionResult ComponentDescriptorsXml()
        {
            using(var dataContext = new ComponentoDataContext())
            {
                var options = new DataLoadOptions();
                options.LoadWith<Component>(c => c.ComponentClis);
                options.LoadWith<Component>(c => c.ComponentIsas);
                options.LoadWith<Component>(c => c.ComponentLicenses);
                options.LoadWith<Component>(c => c.ComponentManifest);

                dataContext.LoadOptions = options;

                var components = (from c in dataContext.Components
                                  orderby c.Name ascending , c.Version descending
                                  select c).ToList();

                return View(components);
            } // using
        }

        [OutputCache(Location = OutputCacheLocation.Any, Duration = 60, VaryByParam = "*")]
        public ActionResult ComponentManifestXml(string componentName, string componentVersion)
        {
            using(var dataContext = new ComponentoDataContext())
            {
                var component = (from c in dataContext.Components
                                 where c.Name == componentName && c.Version == componentVersion
                                 select c).SingleOrDefault();

                var componentRequest = new ComponentRequest
                    {
                        Component = component,
                        Date = DateTime.Now,
                        Url = Request.Url.ToString(),
                        UserHostAddress = Request.UserHostAddress,
                        UserHostName = Request.UserHostName
                    };

                dataContext.ComponentRequests.InsertOnSubmit(componentRequest);
                dataContext.SubmitChanges();

                return Content(component.ComponentManifest.Manifest, "text/xml", Encoding.UTF8);
            } // using
        }
    }
}
